# 使用KMEANS进行密度聚类

import pandas as pd    # 读取csv 文件
import matplotlib.pyplot as plt   # 画图
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler

# 0 读取csv文件

file_path = '202412\\花洒分类\\files\\左0-2000ml-2-2024-12-10-22-43-58_point_cloud.csv'
df = pd.read_csv(file_path)
# print(df.head())

frame_index_all = list(set(df['FrameIndex']))
# print(frame_index_all)

for frame_index in frame_index_all[:10]:

    # 1 对需要的坐标进行画图
    # frame_index = 1 
    # print(df['FrameIndex'])
    frame_data = df[df['FrameIndex'] == frame_index].copy()
    # print(frame_data.shape)
    X = frame_data[[' X', '     Y']]
    # print(frame_data)
    # 绘制x,y的散点图
    plt.figure(figsize=(8, 6))
    plt.scatter(frame_data[' X'], frame_data['     Y'], label=f'FameIndex{frame_index}', color='b')
    # 设置图像标题和标签
    plt.title(f'Points Distribution for FrameIndex {frame_index}', fontsize=14)
    plt.xlabel('X', fontsize=12)
    plt.ylabel('Y', fontsize=12)
    plt.grid(True)
    plt.legend()
    plt.savefig(f'202412\\花洒分类\\kmean_res\\左0-2000ml-2-2024-12-10-22-43-58_point_cloud_{frame_index}.png')
    # plt.show()
    plt.close() 

    # 2 使用聚类算法对需要的坐标进行画图

    # 对数据进行标准化
    scaler = StandardScaler()
    X_scaled = scaler.fit_transform(X)

    # 使用KMEANS进行聚类
    kmeans = KMeans(n_clusters=2, random_state=42)  # 选择的聚类的数目
    kmeans.fit_predict(X_scaled)
    labels = kmeans.labels_
    # print(labels)
    unique_labels = set(labels)

    # 将结果加入原数据中
    frame_data['Cluster'] = labels

    # 获取每个簇的质心
    centroids = kmeans.cluster_centers_

    # 使用不同颜色绘制每个聚类的点
    for label in unique_labels:
        label_data = frame_data[frame_data['Cluster'] == label]
        plt.scatter(label_data[' X'], label_data['     Y'], label=f'Cluster {label}')
        # plt.scatter(centroids[:, 0], centroids[:, 1], s=200, c='red', marker='x', label='Centroids')  # 绘制质心

    # # 绘制聚类结果
    # plt.scatter(frame_data[' X'], frame_data['     Y'], c=labels, cmap='viridis', s=50, alpha=0.6)  # 绘制带颜色的点图


    plt.title("KMeans Clustering Results on X, Y Coordinates", fontsize=14)
    plt.xlabel("X", fontsize=12)
    plt.ylabel("Y", fontsize=12)
    plt.legend()
    plt.grid(True)
    plt.savefig(f'202412\\花洒分类\\kmean_res\\左0-2000ml-2-2024-12-10-22-43-58_point_cloud_{frame_index}_cluster.png')
    # plt.show()
    plt.close()
    # 4 保存
